package vip.meeet.mysql.helper;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class SSHClient {

    public static void main(String[] args) {
        exec();
    }

    /**
     * 直接执行命令
     */
    public static void exec() {
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession("ubuntu", "106.52.114.146", 22);
            JschUserInfo ui = new JschUserInfo();
            ui.setPassword("(_txy2019_)");
            session.setUserInfo(ui);
            session.connect();
            String cmd = "ps -ef|grep -v grep|grep java";
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmd);
            InputStream in = channel.getInputStream();
            OutputStream out = channel.getOutputStream();
            ((ChannelExec) channel).setErrStream(System.err);

            channel.connect();
            out.flush();

            System.out.println((IOUtils.toString(in, Charset.forName("utf-8"))));
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * sudo + cmd的形式
     */
    public void execWithSudo() {
        JSch jsch = new JSch();
        try {
            String password = "testuser1";
            Session session = jsch.getSession("omc", "192.168.101.35", 22);
            JschUserInfo ui = new JschUserInfo();
            ui.setPassword(password);
            session.setUserInfo(ui);
            session.connect();
            String cmd = "sudo -S -p '' systemctl start sasHandler";
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmd);
            InputStream in = channel.getInputStream();
            OutputStream out = channel.getOutputStream();
            ((ChannelExec) channel).setErrStream(System.err);

            channel.connect();

            out.write((password + "\n").getBytes());
            out.flush();

            System.out.println((IOUtils.toString(in, Charset.forName("utf-8"))));
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
